#include "register.h"
#include "ui_register.h"
#include "mysql.h"
#include <QDateTime>
#include <QSqlQuery>

Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
}

Register::~Register()
{
    delete ui;
}

void Register::on_registerBtn_clicked()
{
    QString id = ui->accountEdit->text().trimmed();
    QString pwd = ui->passwordEdit->text();
    QString confirmPwd = ui->confirmPwdEdit->text();
    QString question = ui->secretQEdit->text().trimmed();
    QString answer = ui->secretAEdit->text().trimmed();

    if (id.isEmpty() || pwd.isEmpty() || confirmPwd.isEmpty() || question.isEmpty() || answer.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写完整信息！");
        return;
    }
    if (pwd != confirmPwd) {
        QMessageBox::warning(this, "提示", "两次输入的密码不一致！");
        return;
    }
    if (!db.initDatabase()) {
        QMessageBox::critical(this, "错误", "数据库连接失败！");
        return;
    }
    if (db.checkAccount(id)) {
        QMessageBox::warning(this, "提示", "该账号已存在！");
        return;
    }
    QSqlQuery query(db.getDatabase());
    query.prepare("INSERT INTO users (id, password, question, answer, register_time) VALUES (?, ?, ?, ?, ?)");
    query.addBindValue(id);
    query.addBindValue(pwd);
    query.addBindValue(question);
    query.addBindValue(answer);
    query.addBindValue(QDateTime::currentDateTime());
    if (query.exec()) {
        QMessageBox::information(this, "提示", "注册成功！");
        emit registerSuccess();
        this->close();
    } else {
        QMessageBox::critical(this, "错误", "注册失败：" + query.lastError().text());
    }
}
